//
//  ILGJSLiveTool.m
//  IfengLiveRecord
//
//  Created by zhangtongle-Pro on 2017/9/8.
//  Copyright © 2017年 凤凰新媒体. All rights reserved.
//

#import "ILGJSLiveTool.h"

#if __has_include("libksygpulive/libksygpulive")

#import <libksygpulive/libksygpulive.h>
#import <libksygpulive/KSYGPUStreamerKit.h>

@interface ILGJSLiveTool ()
@property (nonatomic,strong) KSYGPUStreamerKit * ksyGPUStreamerkit;

@end

//#endif

@implementation ILGJSLiveTool

//#if __has_include(<libksygpulive/libksygpulive>)

- (void)startPreview:(UIView *)view
{
    [self.ksyGPUStreamerkit startPreview:view];
    
    [self.ksyGPUStreamerkit.preview setFillMode:kGPUImageFillModePreserveAspectRatioAndFill];
}
- (void)startPreview:(UIView *)view inDirection:(UIInterfaceOrientation)direction
{
    self.ksyGPUStreamerkit.videoOrientation = direction;
    [self.ksyGPUStreamerkit startPreview:view];
    
    [self.ksyGPUStreamerkit.preview setFillMode:kGPUImageFillModePreserveAspectRatioAndFill];
}
- (void)stopPreview
{
    [self.ksyGPUStreamerkit stopPreview];
}

- (void)startPush:(NSString *)urlString
{
    [self.ksyGPUStreamerkit.streamerBase startStream:[NSURL URLWithString:urlString]];
}
- (void)pausePush
{
    [self.ksyGPUStreamerkit.streamerBase stopStream];
}
- (void)stopPush
{
    [self.ksyGPUStreamerkit.streamerBase stopStream];
}

- (void)switchCamera
{
    [super switchCamera];
    [self.ksyGPUStreamerkit switchCamera];
}

- (AVCaptureDevicePosition)cameraPosition {
    return self.ksyGPUStreamerkit.cameraPosition;
}

- (void)adjustBeautyValue:(CGFloat)value
{
    [super adjustBeautyValue:value];
    
    int beautyLevel = value/2.0 + 0.5;
    if (beautyLevel <= 0) {
        beautyLevel = 1;
    }
    if (beautyLevel > 5) {
        beautyLevel = 5;
    }

    KSYGPUBeautifyExtFilter *curFilter = [[KSYGPUBeautifyExtFilter alloc] init];
    [curFilter setBeautylevel:beautyLevel];
    [self.ksyGPUStreamerkit setupFilter:curFilter];
}
//- (CGFloat)currentBeautyValue
//{
//    return self.beautyValue;
//}

- (double)videoUploadBitrate
{
    return self.ksyGPUStreamerkit.streamerBase.currentUploadingKbps;
}

#pragma mark - 初始化

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self configure];
        [self addObserver];
    }
    
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)configure
{
    self.ksyGPUStreamerkit = [[KSYGPUStreamerKit alloc] initWithDefaultCfg];
    
    self.ksyGPUStreamerkit.streamerBase.videoCodec = KSYVideoCodec_VT264;
    self.ksyGPUStreamerkit.streamerBase.audioCodec = KSYAudioCodec_AAC_HE_V2;
    self.ksyGPUStreamerkit.streamerProfile = KSYStreamerProfile_540p_2;
    
    self.ksyGPUStreamerkit.streamerBase.videoInitBitrate = 500; // k bit ps
    self.ksyGPUStreamerkit.streamerBase.videoMaxBitrate  = 800; // k bit ps
    self.ksyGPUStreamerkit.streamerBase.videoMinBitrate  = 500; // k bit ps
    self.ksyGPUStreamerkit.streamerBase.audiokBPS        = 32; // k bit ps
    
    self.ksyGPUStreamerkit.streamerBase.maxKeyInterval = 3;
    self.ksyGPUStreamerkit.streamerBase.videoEncodePerf = KSYVideoEncodePer_Balance;
    self.ksyGPUStreamerkit.streamerBase.liveScene = KSYLiveScene_Default;//设置录制场景。通用或秀场。
    self.ksyGPUStreamerkit.streamerBase.recScene = KSYRecScene_ConstantQuality;
    self.ksyGPUStreamerkit.streamerBase.bwEstimateMode = KSYBWEstMode_Default;//带宽预估模式。综合平稳模式或流畅优先模式。
    self.ksyGPUStreamerkit.streamerBase.shouldEnableKSYStatModule = YES;
    self.ksyGPUStreamerkit.streamerBase.logBlock = ^(NSString* str){
    };
    
    //配置滤镜
    [self adjustBeautyValue:6];
    
    //采集相关信息
    self.ksyGPUStreamerkit.cameraPosition = self.cameraPosition == AVCaptureDevicePositionBack ? AVCaptureDevicePositionBack:AVCaptureDevicePositionFront;
    self.ksyGPUStreamerkit.gpuOutputPixelFormat = kCVPixelFormatType_32BGRA;
    self.ksyGPUStreamerkit.capturePixelFormat = kCVPixelFormatType_32BGRA;
    
    self.ksyGPUStreamerkit.videoOrientation = UIInterfaceOrientationLandscapeRight;
    
    self.ksyGPUStreamerkit.previewDimension = CGSizeMake(960, 540); //预览分辨率
    self.ksyGPUStreamerkit.streamDimension = CGSizeMake(960, 540); //推流分辨率
    self.ksyGPUStreamerkit.capPreset = AVCaptureSessionPresetiFrame960x540; //采集分辨率
    
    self.ksyGPUStreamerkit.videoFPS = 25; //采集帧率
    
    /*
    self.ksyGPUStreamerkit.videoProcessingCallback = ^(CMSampleBufferRef sampleBuffer){
        //        processVideo(sampleBuffer);
        // 在此处添加自定义图像处理, 直接修改buf中的图像数据会传递到观众端
        // 或复制图像数据之后再做其他处理, 则观众端仍然看到处理前的图像
    };
    self.ksyGPUStreamerkit.audioProcessingCallback = ^(CMSampleBufferRef buf){
        // 在此处添加自定义音频处理, 直接修改buf中的pcm数据会传递到观众端
        // 或复制音频数据之后再做其他处理, 则观众端仍然听到原始声音
    };
    self.ksyGPUStreamerkit.interruptCallback = ^(BOOL bInterrupt){
        // 在此处添加自定义图像采集被打断的处理 (比如接听电话等)
    };
     */
}

- (void)addObserver
{
    NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
    [notifCenter addObserver:self selector:@selector(onStreamStateChange:) name:KSYStreamStateDidChangeNotification object:nil];
    [notifCenter addObserver:self selector:@selector(onNetStateEvent:) name:KSYNetStateEventNotification object:nil];
}

- (void)onStreamStateChange:(NSNotification *)notification
{
    NSString * streamState ;
    int state = self.ksyGPUStreamerkit.streamerBase.streamState;
    if (self.ksyGPUStreamerkit.streamerBase.streamState == KSYStreamStateIdle) {
        streamState = @"state idle";
        
    } else if (self.ksyGPUStreamerkit.streamerBase.streamState == KSYStreamStateConnected){
        streamState = @"connected";
        
    } else if (self.ksyGPUStreamerkit.streamerBase.streamState == KSYStreamStateConnecting ) {
        streamState = @"connecting";
        
    } else if (self.ksyGPUStreamerkit.streamerBase.streamState == KSYStreamStateDisconnecting ) {
        streamState = @"disconnecting";
        
    } else if (self.ksyGPUStreamerkit.streamerBase.streamState == KSYStreamStateError ) {
        streamState = @"stream error";
    }
    NSLog(@"stream state: %lu [%@]", (unsigned long)self.ksyGPUStreamerkit.streamerBase.streamState, streamState);
    
    if ([self.delegate respondsToSelector:@selector(ILGStreamStateChanged:)]) {
        [self.delegate ILGStreamStateChanged:state];
    }
}

- (void)onNetStateEvent:(NSNotification *)notification
{
    KSYNetStateCode netEvent = self.ksyGPUStreamerkit.streamerBase.netStateCode;
    //NSLog(@"net event : %ld", (unsigned long)netEvent );
    if ( netEvent == KSYNetStateCode_SEND_PACKET_SLOW ) {
        NSLog(@"bad network" );
        if ([self.delegate respondsToSelector:@selector(ILGStreamStateChanged:)]) {
            [self.delegate ILGStreamStateChanged:ILGStreamStateBadNetwork];
        }
    }
    else if ( netEvent == KSYNetStateCode_EST_BW_RAISE ) {
        NSLog(@"bitrate raising" );
    }
    else if ( netEvent == KSYNetStateCode_EST_BW_DROP ) {
        NSLog(@"bitrate dropping" );
    }
    else if ( netEvent == KSYNetStateCode_KSYAUTHFAILED ) {
        NSLog(@"SDK auth failed, SDK will stop stream in a few minius" );
    }
}

#endif
@end
